package com.cn.springcloudwechat.controller.ueditorUpload;

import com.cn.springcloudwechat.common.ajax.AjaxRes;
import com.cn.springcloudwechat.mapper.mapper.attachment.YmAttachmentMapper;
import com.cn.springcloudwechat.model.attachment.YmAttachment;
import com.cn.springcloudwechat.upload.CosUtils;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 *  ueditor 图片上传
 * @author: Administrator
 * @create: 2018/7/24 11:48
 */
@Controller
@RequestMapping(value="/resource/upload")
public class UploadAccessoryController {
    private static String  BASEPATH_URL="http://vaccine-1254069518.cos.ap-chengdu.myqcloud.com:80/";
    //COS服务器
    private static final String ATTACHMENT_TYPE_COS="3";
    @Autowired
    YmAttachmentMapper ymAttachmentMapper;
    /**
     * 上传文件 ---ueditor 专用
     * @param file
     * @param request
     * @return MultipartFile uploadFile,
     */
    @ResponseBody
    @RequestMapping(value="/uploadAccessory",method = RequestMethod.POST)
    public Map<String, Object> uploadImages (@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse resp)throws IOException{
        Map<String, Object> params=  uploadAttachment(file,request);
        return params;
    }

    /**
     * 上传文件
     * @param file
     * @param request
     * @return MultipartFile uploadFile,
     */
    @ResponseBody
    @RequestMapping(value="/uploadAlltachment",method = RequestMethod.POST)
    public AjaxRes uploadAlltachment (@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, AjaxRes ajaxRes,HttpServletResponse resp)throws IOException{
        Map<String, Object> params=  uploadAttachment(file,request);
        YmAttachment ymAttachment=new YmAttachment();
        ymAttachment.setAttachmentName(params.get("filename").toString());
        ymAttachment.setAttachmentSuffix(params.get("type").toString());
        ymAttachment.setAttachmentUrl(params.get("url").toString());
        ymAttachment.setAttachmentType(ATTACHMENT_TYPE_COS);
        long attachmentId=  ymAttachmentMapper.insertSelective(ymAttachment);
        ajaxRes.setSucceed(ymAttachment);
        return ajaxRes;
    }



    /**
     *  文件上传
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    private Map<String,Object> uploadAttachment(MultipartFile file,HttpServletRequest request) throws IOException{
        Map<String, Object> params = new HashMap<String, Object>();
        if (file == null) {
            System.out.println("未获得上传文件!");
            return null;
        }
            String filetype = request.getParameter("filetype") + "";
            System.out.println("filetype:" + filetype);
            String basePath = "";
            basePath = request.getSession().getServletContext().getRealPath("upload");
            System.out.println("filename:" + file.getOriginalFilename());
            String ext = file.getOriginalFilename();
            String fileName = String.valueOf(System.currentTimeMillis()).concat("_").concat( Math.random()+"").concat(".").concat(ext);
            StringBuilder sb = new StringBuilder();
            //拼接保存路径
            sb.append(basePath).append("/").append(fileName);
            String visitUrl = basePath.concat("/" + fileName);
            String path=sb.toString();
            if(path.contains("png")){
                path=path.replace(".png", ".jpg");
            }
            File f = new File(path);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            file.transferTo(f);
            if(path.contains("jpg")||path.contains("jpeg")||path.contains("bmp") ){
                Thumbnails.of(path).scale(1f).outputQuality(0.8f).outputFormat("jpg").toFile(f);
                //压缩文件
                File tempFileCompress = new File(path);
                if (!tempFileCompress.getParentFile().exists()) {
                    tempFileCompress.getParentFile().mkdirs();
                }
                f=tempFileCompress;
            }
            basePath = CosUtils.SimpleUploadFileFromLocal(f);
            System.out.println(basePath);
            f.delete();
            String filePath=basePath;
            params.put("state", "SUCCESS");
            params.put("url", filePath);
            params.put("size", file.getSize());
            params.put("original", fileName);
            params.put("type", file.getContentType());
            params.put("filename", file.getOriginalFilename());
        return params;
    }

    }
